using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Input.Touch;
using Microsoft.Xna.Framework.Media;
using System.IO.IsolatedStorage;
using System.IO;
using CauBeTimMe.screen;
using CauBeTimMe.utils;


namespace CauBeTimMe
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Main : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        Screen screen;

        GameScreen gameScreen;
        InputState inputState;
#if DEBUG
        SpriteFont _spr_font;
        int _total_frames = 0;
        float _elapsed_time = 0.0f;
        int _fps = 0;
#endif

        static Main self;

        public static Main getInstance()
        {
            return self;
        }


        public Main()
        {
            graphics = new GraphicsDeviceManager(this);
            graphics.IsFullScreen = true;
            graphics.SupportedOrientations = DisplayOrientation.LandscapeLeft;
            graphics.PreferredBackBufferWidth = Global.SCREEN_WIDTH;
            graphics.PreferredBackBufferHeight = Global.SCREEN_HEIGHT;
            self = this;
            graphics.PreparingDeviceSettings += new EventHandler<PreparingDeviceSettingsEventArgs>
            (graphics_PreparingDeviceSettings);
            Content.RootDirectory = "Content";
            
            TargetElapsedTime = TimeSpan.FromTicks(166667);
            //TargetElapsedTime = TimeSpan.FromTicks(333333);
            // Extend battery life under lock.
            InactiveSleepTime = TimeSpan.FromSeconds(1);
        }

        protected override void Initialize()
        {
            //loadFile();
            //init all screen
            gameScreen = new GameScreen();

            //init input state
            inputState = new InputState();
            //start screen

            showGame();
            //enable gesture
            TouchPanel.EnabledGestures = GestureType.VerticalDrag | GestureType.DoubleTap | GestureType.DragComplete;
            base.Initialize();
        }

        protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(GraphicsDevice);
#if DEBUG
            _spr_font = Content.Load<SpriteFont>("font/SpriteFont1");
#endif
        }

        protected override void Update(GameTime gameTime)
        {
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            {
                this.exitGame();
            }

            // Update
#if DEBUG
            _elapsed_time += (float)gameTime.ElapsedGameTime.TotalMilliseconds;

            // 1 Second has passed
            if (_elapsed_time >= 1000.0f)
            {
                _fps = _total_frames;
                _total_frames = 0;
                _elapsed_time = 0;
            }
#endif

            inputState.Update();
            
            screen.update(gameTime);

            foreach (TouchLocation touch in inputState.touchState)
            {
                screen.touchEvent(touch);
            }
            foreach (GestureSample gesture in inputState.Gestures)
            {
                screen.touchEvent(gesture);
            }

            base.Update(gameTime);
        }

        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.Black);

            //draw screen
            screen.render(spriteBatch);

            spriteBatch.Begin();
#if DEBUG
            _total_frames++;
            spriteBatch.DrawString(_spr_font, string.Format("FPS={0}", _fps),
             new Vector2(10.0f, 20.0f), Color.Red);
#endif
            spriteBatch.End();

            base.Draw(gameTime);
        }

        void graphics_PreparingDeviceSettings(object sender, PreparingDeviceSettingsEventArgs e)
        {
            e.GraphicsDeviceInformation.PresentationParameters.PresentationInterval = PresentInterval.One;
        }

        public void showGame()
        {
            screen = gameScreen;
        }


        public void exitGame()
        {
            //SaveToFile();
            this.Exit();
        }

        /*public void loadFile()
        {
            String fileName = "data.sav";
            IsolatedStorageFile savegameStorage = IsolatedStorageFile.GetUserStoreForApplication();
            if (savegameStorage.FileExists(fileName))
            {
                using (IsolatedStorageFileStream fs = savegameStorage.OpenFile(fileName, System.IO.FileMode.Open))
                {
                    StreamReader reader = new StreamReader(fs);
                    string line = reader.ReadLine();
                    string[] pieces = line.Split(':');
                }
            }

        }

        public void SaveToFile()
        {
            String fileName = "data.sav";
            IsolatedStorageFile recordsStorage = IsolatedStorageFile.GetUserStoreForApplication();
            using (IsolatedStorageFileStream fileStream = recordsStorage.OpenFile(fileName, System.IO.FileMode.Create))
            {
                using (StreamWriter writer = new StreamWriter(fileStream))
                {
                    writer.WriteLine(string.Format("{0}:{1}", Global.Maxdrop, Global.Maxlevel));
                    writer.WriteLine(string.Format("{0}", Global.sound));
                }
            }
        }*/

    }
}
